import 'package:flutter/material.dart';
import 'package:base_flutter/src/network/manager.dart';
import '../../models/user_model.dart';
import '../../widgets/skill_tag_widget.dart';
import '../chat/chat_page.dart';
import '../../utils/cached_image_widget.dart';
import '../../utils/logger.dart';

class UserDetailPage extends StatefulWidget {
  final UserModel user;

  const UserDetailPage({
    super.key,
    required this.user,
  });

  @override
  State<UserDetailPage> createState() => _UserDetailPageState();
}

class _UserDetailPageState extends State<UserDetailPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  bool _isFollowing = false;
  bool _isLoading = true;
  UserModel? _userDetail;
  final NetworkManager _networkManager = NetworkManager();
  
  // 商品列表数据
  List<Map<String, dynamic>> _products = [];
  bool _productsLoading = false;
  
  // 动态列表数据
  List<Map<String, dynamic>> _posts = [];
  bool _postsLoading = false;
  
  // 评价列表数据
  List<Map<String, dynamic>> _reviews = [];
  bool _reviewsLoading = false;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _tabController.addListener(_onTabChanged);
    _loadUserDetail();
    _loadProducts(); // 默认加载商品
  }
  
  /// Tab切换监听
  void _onTabChanged() {
    if (!_tabController.indexIsChanging) {
      switch (_tabController.index) {
        case 0:
          if (_products.isEmpty && !_productsLoading) {
            _loadProducts();
          }
          break;
        case 1:
          if (_posts.isEmpty && !_postsLoading) {
            _loadPosts();
          }
          break;
        case 2:
          if (_reviews.isEmpty && !_reviewsLoading) {
            _loadReviews();
          }
          break;
      }
    }
  }

  /// 从后端加载用户详细信息
  Future<void> _loadUserDetail() async {
    setState(() {
      _isLoading = true;
    });

    try {
      Logger.d('USER_DETAIL', '加载用户详情, userId: ${widget.user.id}');
      
      final response = await _networkManager.get(
        '/api/user/profile/${widget.user.id}',
      );

      if (response['code'] == 200 && response['data'] != null) {
        final data = response['data'];
        
        // 将后端数据转换为UserModel
        final userDetail = UserModel(
          id: data['id']?.toString() ?? widget.user.id,
          username: data['username'] ?? widget.user.username,
          email: data['email'] ?? '',
          avatar: data['avatarUrl'] ?? widget.user.avatar,
          bio: data['signature'] ?? '',
          location: '', // 后端暂不返回
          skills: (data['skillTags'] as List<dynamic>?)
                  ?.map((tag) => SkillTag(
                        id: tag['id']?.toString() ?? '',
                        name: tag['tagName'] ?? '',
                        category: tag['tagType'] ?? '技能',
                        level: SkillLevel.intermediate,
                        isCertified: false,
                        createdAt: DateTime.now(),
                      ))
                  .toList() ??
              [],
          rating: widget.user.rating,
          reviewCount: widget.user.reviewCount,
          followersCount: widget.user.followersCount,
          followingCount: widget.user.followingCount,
          isOnline: widget.user.isOnline,
          createdAt: DateTime.now(),
        );

        if (mounted) {
          setState(() {
            _userDetail = userDetail;
            _isLoading = false;
          });
        }
        
        Logger.d('USER_DETAIL', '用户详情加载成功: ${userDetail.username}');
      } else {
        throw Exception(response['message'] ?? '获取用户详情失败');
      }
    } catch (e) {
      Logger.e('USER_DETAIL', '加载用户详情失败: $e');
      if (mounted) {
        setState(() {
          _userDetail = widget.user; // 失败时使用传入的数据
          _isLoading = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载用户详情失败: $e')),
        );
      }
    }
  }

  /// 加载用户商品列表
  Future<void> _loadProducts() async {
    if (_productsLoading) return;
    
    setState(() {
      _productsLoading = true;
    });

    try {
      Logger.d('USER_DETAIL', '加载用户商品, userId: ${widget.user.id}');
      
      final response = await _networkManager.get(
        '/api/user/${widget.user.id}/service-products?page=1&size=20',
      );

      if (response['code'] == 200 && response['data'] != null) {
        final data = response['data'];
        final list = data['list'] as List<dynamic>?;
        
        if (mounted) {
          setState(() {
            _products = list?.map((e) => e as Map<String, dynamic>).toList() ?? [];
            _productsLoading = false;
          });
        }
        
        Logger.d('USER_DETAIL', '商品加载成功: ${_products.length}个');
      } else {
        throw Exception(response['message'] ?? '获取商品列表失败');
      }
    } catch (e) {
      Logger.e('USER_DETAIL', '加载商品失败: $e');
      if (mounted) {
        setState(() {
          _productsLoading = false;
        });
      }
    }
  }

  /// 加载用户动态列表
  Future<void> _loadPosts() async {
    if (_postsLoading) return;
    
    setState(() {
      _postsLoading = true;
    });

    try {
      Logger.d('USER_DETAIL', '加载用户动态, userId: ${widget.user.id}');
      
      final response = await _networkManager.get(
        '/api/user/posts?userId=${widget.user.id}&currentUserId=1&page=1&size=20',
      );

      if (response['code'] == 200 && response['data'] != null) {
        final data = response['data'];
        final list = data['list'] as List<dynamic>?;
        
        if (mounted) {
          setState(() {
            _posts = list?.map((e) => e as Map<String, dynamic>).toList() ?? [];
            _postsLoading = false;
          });
        }
        
        Logger.d('USER_DETAIL', '动态加载成功: ${_posts.length}个');
      } else {
        throw Exception(response['message'] ?? '获取动态列表失败');
      }
    } catch (e) {
      Logger.e('USER_DETAIL', '加载动态失败: $e');
      if (mounted) {
        setState(() {
          _postsLoading = false;
        });
      }
    }
  }

  /// 加载用户评价列表
  Future<void> _loadReviews() async {
    if (_reviewsLoading) return;
    
    setState(() {
      _reviewsLoading = true;
    });

    try {
      Logger.d('USER_DETAIL', '加载用户评价, userId: ${widget.user.id}');
      
      // TODO: 等待后端实现评价接口
      // final response = await _networkManager.get(
      //   '/api/user/${widget.user.id}/reviews?page=1&size=20',
      // );
      
      // 暂时使用空数据
      if (mounted) {
        setState(() {
          _reviews = [];
          _reviewsLoading = false;
        });
      }
      
      Logger.d('USER_DETAIL', '评价加载成功: ${_reviews.length}个');
    } catch (e) {
      Logger.e('USER_DETAIL', '加载评价失败: $e');
      if (mounted) {
        setState(() {
          _reviewsLoading = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _tabController.removeListener(_onTabChanged);
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 显示加载指示器
    if (_isLoading) {
      return Scaffold(
        appBar: AppBar(
          title: const Text('用户详情'),
        ),
        body: const Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    // 使用查询到的用户详情或传入的数据
    final user = _userDetail ?? widget.user;

    return Scaffold(
      body: CustomScrollView(
        slivers: [
          // 自定义AppBar
          SliverAppBar(
            expandedHeight: 300,
            pinned: true,
            flexibleSpace: FlexibleSpaceBar(
              background: _buildUserHeader(user),
            ),
            leading: IconButton(
              icon: const Icon(Icons.arrow_back, color: Colors.white),
              onPressed: () => Navigator.pop(context),
            ),
            actions: [
              IconButton(
                icon: const Icon(Icons.more_vert, color: Colors.white),
                onPressed: () => _showMoreOptions(),
              ),
            ],
          ),
          // 用户信息卡片
          SliverToBoxAdapter(
            child: _buildUserInfoCard(user),
          ),
          // 标签页
          SliverPersistentHeader(
            pinned: true,
            delegate: _SliverAppBarDelegate(
              TabBar(
                controller: _tabController,
                labelColor: Theme.of(context).primaryColor,
                unselectedLabelColor: Colors.grey,
                indicatorColor: Theme.of(context).primaryColor,
                tabs: const [
                  Tab(text: '商品'),
                  Tab(text: '动态'),
                  Tab(text: '交易评论'),
                ],
              ),
            ),
          ),
          // 标签页内容
          SliverFillRemaining(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildProductsTab(user),
                _buildPostsTab(),
                _buildTransactionReviewsTab(),
              ],
            ),
          ),
        ],
      ),
      bottomNavigationBar: _buildBottomActions(user),
    );
  }

  Widget _buildUserHeader(UserModel user) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Theme.of(context).primaryColor,
            Theme.of(context).primaryColor.withOpacity(0.8),
          ],
        ),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const SizedBox(height: 60),
          // 头像
          Container(
            width: 100,
            height: 100,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.white, width: 4),
              color: Colors.grey[300],
              image: user.avatar != null && user.avatar!.isNotEmpty
                  ? DecorationImage(
                      image: NetworkImage(user.avatar!),
                      fit: BoxFit.cover,
                    )
                  : null,
            ),
            child: user.avatar == null || user.avatar!.isEmpty
                ? const Icon(Icons.person, size: 50, color: Colors.grey)
                : null,
          ),
          const SizedBox(height: 16),
          // 用户名和认证标识
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                user.username,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(width: 8),
              if (user.certifications.isNotEmpty)
                const Icon(
                  Icons.verified,
                  color: Colors.amber,
                  size: 24,
                ),
            ],
          ),
          const SizedBox(height: 4),
          // 用户ID
          Text(
            'ID: ${user.id}',
            style: TextStyle(
              color: Colors.white.withOpacity(0.8),
              fontSize: 14,
              fontFamily: 'monospace',
            ),
          ),
          const SizedBox(height: 8),
          // 评分
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.star, color: Colors.amber, size: 20),
              const SizedBox(width: 4),
              Text(
                '${user.rating} (${user.reviewCount}评价)',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildUserInfoCard(UserModel user) {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 3,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 个人简介
          if (user.bio != null && user.bio!.isNotEmpty) ...[
            const Text(
              '个人简介',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              user.bio!,
              style: const TextStyle(fontSize: 14, color: Colors.grey),
            ),
            const SizedBox(height: 16),
          ],
          // 统计信息
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                    '关注者', user.followersCount.toString()),
              ),
              Container(
                width: 1,
                height: 40,
                color: Colors.grey[300],
              ),
              Expanded(
                child: _buildStatItem(
                    '关注中', user.followingCount.toString()),
              ),
              Container(
                width: 1,
                height: 40,
                color: Colors.grey[300],
              ),
              Expanded(
                child:
                    _buildStatItem('技能', user.skills.length.toString()),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value) {
    return Column(
      children: [
        Text(
          value,
          style: const TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          label,
          style: TextStyle(
            color: Colors.grey[600],
            fontSize: 12,
          ),
        ),
      ],
    );
  }

  Widget _buildProductsTab(UserModel user) {
    if (_productsLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_products.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.shopping_bag_outlined, size: 64, color: Colors.grey[400]),
            const SizedBox(height: 16),
            Text(
              '暂无商品',
              style: TextStyle(fontSize: 16, color: Colors.grey[600]),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _products.length,
      itemBuilder: (context, index) {
        final product = _products[index];
        return _buildProductCardFromData(product);
      },
    );
  }

  Widget _buildProductCard({
    required String title,
    required String description,
    required int price,
    required String duration,
    required String category,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    title,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: Theme.of(context).primaryColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Text(
                    category,
                    style: TextStyle(
                      color: Theme.of(context).primaryColor,
                      fontSize: 12,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              description,
              style: const TextStyle(fontSize: 14, color: Colors.grey),
            ),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Text(
                      '¥$price',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: Theme.of(context).primaryColor,
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '/$duration',
                      style: const TextStyle(fontSize: 14, color: Colors.grey),
                    ),
                  ],
                ),
                ElevatedButton(
                  onPressed: () {
                    // 购买服务
                    _showPurchaseDialog(title, price);
                  },
                  child: const Text('购买'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPostsTab() {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        const Text(
          '最新动态',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 16),
        // 示例动态
        _buildPostCard(
          content: '今天完成了一个Flutter项目的重构，性能提升了30%！分享一下技术心得，希望对大家有帮助。',
          images: [''],
          likesCount: 128,
          commentsCount: 15,
          sharesCount: 8,
          createdAt: DateTime.now().subtract(const Duration(hours: 2)),
        ),
        const SizedBox(height: 12),
        _buildPostCard(
          content: '新设计的UI界面获得了客户的一致好评，用户体验得到了显著提升。设计真的是一门艺术！',
          images: [
            '',
            ''
          ],
          likesCount: 256,
          commentsCount: 32,
          sharesCount: 18,
          createdAt: DateTime.now().subtract(const Duration(hours: 4)),
        ),
      ],
    );
  }

  Widget _buildPostCard({
    required String content,
    required List<String> images,
    required int likesCount,
    required int commentsCount,
    required int sharesCount,
    required DateTime createdAt,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              content,
              style: const TextStyle(fontSize: 14),
            ),
            if (images.isNotEmpty) ...[
              const SizedBox(height: 12),
              _buildImageGrid(images),
            ],
            const SizedBox(height: 12),
            Row(
              children: [
                _buildActionButton(
                  icon: Icons.favorite_border,
                  label: '$likesCount',
                  onTap: () {},
                ),
                const SizedBox(width: 24),
                _buildActionButton(
                  icon: Icons.comment,
                  label: '$commentsCount',
                  onTap: () {},
                ),
                const SizedBox(width: 24),
                _buildActionButton(
                  icon: Icons.share,
                  label: '$sharesCount',
                  onTap: () {},
                ),
                const Spacer(),
                Text(
                  _getTimeAgo(createdAt),
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 12,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildImageGrid(List<String> images) {
    if (images.length == 1) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: Image.network(
          images[0],
          width: double.infinity,
          height: 200,
          fit: BoxFit.cover,
        ),
      );
    } else {
      return GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
        ),
        itemCount: images.length > 9 ? 9 : images.length,
        itemBuilder: (context, index) {
          return ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: Image.network(
              images[index],
              fit: BoxFit.cover,
            ),
          );
        },
      );
    }
  }

  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Row(
        children: [
          Icon(
            icon,
            size: 20,
            color: Colors.grey[600],
          ),
          const SizedBox(width: 4),
          Text(
            label,
            style: TextStyle(
              color: Colors.grey[600],
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTransactionReviewsTab() {
    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        const Text(
          '交易评价',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        const SizedBox(height: 16),
        // 示例交易评价
        _buildReviewCard(
          username: '李四',
          avatar: '',
          rating: 5.0,
          content: '服务很专业，技术能力很强，解决问题很及时，推荐！',
          serviceName: 'Flutter开发咨询',
          createdAt: DateTime.now().subtract(const Duration(days: 2)),
        ),
        const SizedBox(height: 12),
        _buildReviewCard(
          username: '王五',
          avatar: '',
          rating: 4.5,
          content: '技术功底扎实，沟通顺畅，项目完成得很满意。',
          serviceName: 'React项目重构',
          createdAt: DateTime.now().subtract(const Duration(days: 5)),
        ),
      ],
    );
  }

  Widget _buildReviewCard({
    required String username,
    required String avatar,
    required double rating,
    required String content,
    required String serviceName,
    required DateTime createdAt,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                CachedAvatarWidget(
                  avatarUrl: avatar,
                  size: 40,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        username,
                        style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                      ),
                      Row(
                        children: [
                          ...List.generate(5, (index) {
                            return Icon(
                              index < rating.floor()
                                  ? Icons.star
                                  : Icons.star_border,
                              color: Colors.amber,
                              size: 16,
                            );
                          }),
                          const SizedBox(width: 8),
                          Text(
                            rating.toString(),
                            style: const TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
                Text(
                  _getTimeAgo(createdAt),
                  style: TextStyle(
                    color: Colors.grey[600],
                    fontSize: 12,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                serviceName,
                style: TextStyle(
                  color: Colors.grey[700],
                  fontSize: 12,
                ),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              content,
              style: const TextStyle(fontSize: 14),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCertificationItem(Certification cert) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: _getCertificationStatusColor(cert.status),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.verified,
            color: _getCertificationStatusColor(cert.status),
            size: 20,
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  cert.title,
                  style: const TextStyle(
                    fontWeight: FontWeight.w500,
                  ),
                ),
                if (cert.description != null) ...[
                  const SizedBox(height: 4),
                  Text(
                    cert.description!,
                    style: TextStyle(
                      color: Colors.grey[600],
                      fontSize: 12,
                    ),
                  ),
                ],
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              color: _getCertificationStatusColor(cert.status).withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Text(
              _getCertificationStatusText(cert.status),
              style: TextStyle(
                color: _getCertificationStatusColor(cert.status),
                fontSize: 12,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Color _getCertificationStatusColor(CertificationStatus status) {
    switch (status) {
      case CertificationStatus.approved:
        return Colors.green;
      case CertificationStatus.pending:
        return Colors.orange;
      case CertificationStatus.rejected:
        return Colors.red;
      case CertificationStatus.expired:
        return Colors.grey;
    }
  }

  String _getCertificationStatusText(CertificationStatus status) {
    switch (status) {
      case CertificationStatus.approved:
        return '已通过';
      case CertificationStatus.pending:
        return '审核中';
      case CertificationStatus.rejected:
        return '已拒绝';
      case CertificationStatus.expired:
        return '已过期';
    }
  }

  Widget _buildBottomActions(UserModel user) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.1),
            spreadRadius: 1,
            blurRadius: 3,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: OutlinedButton.icon(
              onPressed: () {
                setState(() {
                  _isFollowing = !_isFollowing;
                });
                _showFollowDialog();
              },
              icon: Icon(_isFollowing ? Icons.person_remove : Icons.person_add),
              label: Text(_isFollowing ? '取消关注' : '关注'),
              style: OutlinedButton.styleFrom(
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: ElevatedButton.icon(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => ChatPage(targetUser: user),
                  ),
                );
              },
              icon: const Icon(Icons.chat),
              label: const Text('咨询'),
            ),
          ),
        ],
      ),
    );
  }

  void _showMoreOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.report),
              title: const Text('举报'),
              onTap: () {
                Navigator.pop(context);
                // 处理举报逻辑
              },
            ),
            ListTile(
              leading: const Icon(Icons.block),
              title: const Text('拉黑'),
              onTap: () {
                Navigator.pop(context);
                // 处理拉黑逻辑
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showFollowDialog() {
    if (_isFollowing) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('关注分类'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('请选择关注分类：'),
              const SizedBox(height: 16),
              _buildCategoryChips(),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
                // 处理关注逻辑
              },
              child: const Text('确定'),
            ),
          ],
        ),
      );
    }
  }

  Widget _buildCategoryChips() {
    final categories = ['技术', '设计', '咨询', '教育', '其他'];
    return Wrap(
      spacing: 8,
      children: categories.map((category) {
        return FilterChip(
          label: Text(category),
          onSelected: (selected) {
            // 处理分类选择
          },
        );
      }).toList(),
    );
  }

  void _showPurchaseDialog(String serviceName, int price) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('购买服务'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('确定要购买"$serviceName"服务吗？'),
            const SizedBox(height: 8),
            Text(
              '价格：¥$price',
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.red,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              // 处理购买逻辑
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('购买功能开发中...')),
              );
            },
            child: const Text('确认购买'),
          ),
        ],
      ),
    );
  }

  String _getTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  /// 从真实数据构建商品卡片
  Widget _buildProductCardFromData(Map<String, dynamic> product) {
    final title = product['title'] ?? '未命名商品';
    final description = product['description'] ?? '';
    final price = product['price'] ?? 0.0;
    final priceDisplay = product['priceDisplay'] ?? '¥$price';
    final durationDisplay = product['durationDisplay'] ?? '';
    final coverUrl = product['coverUrl'];
    final isAvailable = product['isAvailable'] ?? true;
    final likesCount = product['likesCount'] ?? 0;
    final viewsCount = product['viewsCount'] ?? 0;

    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: InkWell(
        onTap: isAvailable ? () => _showProductDetail(product) : null,
        borderRadius: BorderRadius.circular(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 商品封面图
            if (coverUrl != null && coverUrl.toString().isNotEmpty)
              ClipRRect(
                borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
                child: Image.network(
                  coverUrl,
                  width: double.infinity,
                  height: 180,
                  fit: BoxFit.cover,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      height: 180,
                      color: Colors.grey[200],
                      child: Icon(Icons.image_not_supported, size: 64, color: Colors.grey[400]),
                    );
                  },
                ),
              ),
            Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 标题和价格
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          title,
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const SizedBox(width: 12),
                      Text(
                        priceDisplay,
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: Theme.of(context).primaryColor,
                        ),
                      ),
                    ],
                  ),
                  if (description.isNotEmpty) ...[
                    const SizedBox(height: 8),
                    Text(
                      description,
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[600],
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                  const SizedBox(height: 12),
                  // 时长和互动数据
                  Row(
                    children: [
                      if (durationDisplay.isNotEmpty) ...[
                        Icon(Icons.access_time, size: 16, color: Colors.grey[600]),
                        const SizedBox(width: 4),
                        Text(
                          durationDisplay,
                          style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                        ),
                        const SizedBox(width: 16),
                      ],
                      Icon(Icons.visibility, size: 16, color: Colors.grey[600]),
                      const SizedBox(width: 4),
                      Text(
                        '$viewsCount',
                        style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                      ),
                      const SizedBox(width: 16),
                      Icon(Icons.favorite_border, size: 16, color: Colors.grey[600]),
                      const SizedBox(width: 4),
                      Text(
                        '$likesCount',
                        style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                      ),
                      const Spacer(),
                      // 购买按钮
                      ElevatedButton(
                        onPressed: isAvailable ? () => _buyProduct(product) : null,
                        style: ElevatedButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                          ),
                        ),
                        child: Text(isAvailable ? '立即购买' : '已下架'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 显示商品详情
  void _showProductDetail(Map<String, dynamic> product) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) {
        final title = product['title'] ?? '未命名商品';
        final description = product['description'] ?? '';
        final priceDisplay = product['priceDisplay'] ?? '';
        final durationDisplay = product['durationDisplay'] ?? '';
        final location = product['location'] ?? '';
        final isOnline = product['isOnline'] ?? false;
        
        return DraggableScrollableSheet(
          initialChildSize: 0.7,
          minChildSize: 0.5,
          maxChildSize: 0.95,
          expand: false,
          builder: (context, scrollController) {
            return SingleChildScrollView(
              controller: scrollController,
              padding: const EdgeInsets.all(24),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 拖动指示器
                  Center(
                    child: Container(
                      width: 40,
                      height: 4,
                      decoration: BoxDecoration(
                        color: Colors.grey[300],
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),
                  // 标题
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 16),
                  // 价格
                  Text(
                    priceDisplay,
                    style: TextStyle(
                      fontSize: 28,
                      fontWeight: FontWeight.bold,
                      color: Theme.of(context).primaryColor,
                    ),
                  ),
                  const SizedBox(height: 24),
                  // 服务信息
                  if (durationDisplay.isNotEmpty || location.isNotEmpty) ...[
                    const Text(
                      '服务信息',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 12),
                    if (durationDisplay.isNotEmpty)
                      _buildInfoRow(Icons.access_time, '服务时长', durationDisplay),
                    if (location.isNotEmpty)
                      _buildInfoRow(Icons.location_on, '服务地点', location),
                    _buildInfoRow(Icons.computer, '服务方式', isOnline ? '在线服务' : '线下服务'),
                    const SizedBox(height: 24),
                  ],
                  // 描述
                  const Text(
                    '服务描述',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Text(
                    description.isNotEmpty ? description : '暂无描述',
                    style: const TextStyle(fontSize: 14, height: 1.6),
                  ),
                  const SizedBox(height: 32),
                  // 购买按钮
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: () {
                        Navigator.pop(context);
                        _buyProduct(product);
                      },
                      style: ElevatedButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: const Text(
                        '立即购买',
                        style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildInfoRow(IconData icon, String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        children: [
          Icon(icon, size: 20, color: Colors.grey[600]),
          const SizedBox(width: 12),
          Text(
            '$label：',
            style: TextStyle(fontSize: 14, color: Colors.grey[600]),
          ),
          Text(
            value,
            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
          ),
        ],
      ),
    );
  }

  /// 购买商品
  Future<void> _buyProduct(Map<String, dynamic> product) async {
    final serviceProductId = product['id'];
    final price = product['price'] ?? 0.0;
    final title = product['title'] ?? '未命名商品';

    // 显示确认对话框
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认购买'),
        content: Text('确定要购买"$title"吗？\n价格：¥$price'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('确认'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    try {
      Logger.d('USER_DETAIL', '创建订单, serviceProductId: $serviceProductId');

      // 1. 创建订单
      final createResponse = await _networkManager.post(
        '/api/orders/create',
        data: {
          'serviceProductId': serviceProductId,
          'quantity': 1,
        },
      );

      if (createResponse['code'] != 200) {
        throw Exception(createResponse['message'] ?? '创建订单失败');
      }

      final orderData = createResponse['data'];
      final orderId = orderData['orderId'];
      final orderNo = orderData['orderNo'];

      Logger.d('USER_DETAIL', '订单创建成功, orderId: $orderId, orderNo: $orderNo');

      // 2. 显示支付选择对话框
      if (mounted) {
        _showPaymentDialog(orderId, orderNo, price);
      }
    } catch (e) {
      Logger.e('USER_DETAIL', '购买失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('购买失败: $e')),
        );
      }
    }
  }

  /// 显示支付对话框
  void _showPaymentDialog(int orderId, String orderNo, double amount) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择支付方式'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('订单号：$orderNo'),
            const SizedBox(height: 8),
            Text(
              '支付金额：¥$amount',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: Theme.of(context).primaryColor,
              ),
            ),
            const SizedBox(height: 24),
            // 支付方式选择
            ListTile(
              leading: const Icon(Icons.account_balance_wallet),
              title: const Text('余额支付'),
              subtitle: const Text('使用账户余额支付'),
              onTap: () {
                Navigator.pop(context);
                _payOrder(orderId, 'balance');
              },
            ),
            ListTile(
              leading: const Icon(Icons.payment),
              title: const Text('微信支付'),
              subtitle: const Text('暂未开通'),
              enabled: false,
            ),
            ListTile(
              leading: const Icon(Icons.payment),
              title: const Text('支付宝'),
              subtitle: const Text('暂未开通'),
              enabled: false,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  /// 支付订单
  Future<void> _payOrder(int orderId, String paymentMethod) async {
    try {
      Logger.d('USER_DETAIL', '支付订单, orderId: $orderId, method: $paymentMethod');

      final response = await _networkManager.post(
        '/api/orders/$orderId/pay',
        data: {
          'paymentMethod': paymentMethod,
        },
      );

      if (response['code'] != 200) {
        throw Exception(response['message'] ?? '支付失败');
      }

      final orderData = response['data'];
      Logger.d('USER_DETAIL', '支付成功: $orderData');

      if (mounted) {
        // 显示支付成功对话框
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('支付成功'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const Icon(Icons.check_circle, size: 64, color: Colors.green),
                const SizedBox(height: 16),
                Text('订单号：${orderData['orderNo']}'),
                const SizedBox(height: 8),
                const Text('支付成功！'),
                // 如果是虚拟商品，显示提取信息
                if (orderData['virtualContent'] != null) ...[
                  const SizedBox(height: 16),
                  const Divider(),
                  const SizedBox(height: 8),
                  const Text(
                    '虚拟商品内容',
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 8),
                  if (orderData['virtualContent']['downloadUrl'] != null)
                    Text('下载地址：${orderData['virtualContent']['downloadUrl']}'),
                  if (orderData['virtualContent']['accessCode'] != null)
                    Text('提取码：${orderData['virtualContent']['accessCode']}'),
                ],
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      Logger.e('USER_DETAIL', '支付失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('支付失败: $e')),
        );
      }
    }
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar _tabBar;

  _SliverAppBarDelegate(this._tabBar);

  @override
  double get minExtent => _tabBar.preferredSize.height;

  @override
  double get maxExtent => _tabBar.preferredSize.height;

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.white,
      child: _tabBar,
    );
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return false;
  }
}
